import {emitter} from '@/utils/bus.js';

let websocket = null;
let isConnect = false;

export const sendMessage = (data) => {
  if (isConnect && websocket) {
    websocket.send(JSON.stringify(data));
  }
};

export const connectWebsocket = () => {
  if (websocket != null) return;

  if (!("WebSocket" in window)) return;

  let host = window.location.host;
  let url = "ws://" + host + import.meta.env.VITE_BASE_PATH + "/websocket"
  websocket = new WebSocket(url);

  websocket.onopen = () => {
    isConnect = true;
    console.log("websocket连接成功。")
  };

  websocket.onmessage = (message) => {
    if (message.type !== 'message') return;

    let data = JSON.parse(message.data);
    emitter.emit(data.type, JSON.parse(data.data));
  };

  websocket.onclose = () => {
    isConnect = false;
    console.log("websocket连接关闭。");
  };

  websocket.onerror = () => {
    console.log("websocket连接异常。");
  };
};
